/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sun.distributor.dao;

import com.sun.distributor.exceptions.InitException;
import com.sun.distributor.exceptions.QueryException;
import com.sun.distributor.exceptions.SystemException;
import com.sun.distributor.objects.Product;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrateur
 */
public class DAO_Product extends Abstract_DAO {

    DAO_ProductType pdDAO;

    public void insertProduct(Product prod) throws QueryException, SystemException {
        try {
            Connection c = getConnection();
            Statement stmt = c.createStatement();
            try {
                StringBuilder sqlString = new StringBuilder("insert into soa_product(productName, ProductPrice, Product_Type_idProduct_Type)");

                sqlString.append("values ('").append(prod.getProductName()).append("', ");
                sqlString.append(prod.getProductPrice()).append(",");
                sqlString.append(prod.getProduct_Type().getIdProduct_Type()).append(")");

                stmt.execute(sqlString.toString());

            } catch (SQLException ex) {
                throw new QueryException(ex);
            } finally {
                stmt.close();

            }
        } catch (Exception ex) {
            throw new SystemException(ex);
        }
    }

    public Product getProduct(int id) throws SystemException {
        try {
            pdDAO = new DAO_ProductType();
            Connection c = getConnection();
            Statement stmt = c.createStatement();
            try {
                ResultSet rs = stmt.executeQuery("select * from soa_product where idProduct=" + id);
                Product prod;
                if (rs.next()) {
                    prod = new Product(rs.getInt("idProduct"), rs.getString("productName"), rs.getInt("productPrice"));
                    prod.setProduct_Type(pdDAO.getProductType(rs.getInt("Product_Type_idProduct_Type")));
                } else {
                    return null;
                }
                return prod;
            } catch (SQLException ex) {
                throw new SystemException(ex);
            } finally {
                stmt.close();
                c.close();
            }
        } catch (SQLException ex) {
            throw new SystemException(ex);
        } catch (InitException ex) {
            throw new SystemException(ex);
        }

    }
}
